#include <iostream>
#include <cstring>
#include <cerrno>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <unistd.h>
#include "err.hpp"

using namespace std;

void usage(std::string proc)
{
    cout << "Usage:\n\t" << proc << " serverip serverport" << endl;
}

int main(int args, char *argv[])
{
    if (args != 3)
    {
        usage(argv[0]);
        exit(USAGE_ERR);
    }

    std::string server_ip = argv[1];
    uint16_t server_port = atoi(argv[2]);

    int sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock < 0)
    {
        cerr << "create socket error" << endl;
        exit(SOCKET_ERR);
    }

    struct sockaddr_in server;
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = inet_addr(server_ip.c_str());
    server.sin_port = htons(server_port);

    int cnt = 1;
    while (connect(sock, (sockaddr *)&server, sizeof(server)) != 0)
    {
        cout << "正在重连(" << cnt++ << ")" << endl;
        sleep(1);
        if (cnt > 5)
            break;
    }

    if (cnt > 5)
    {
        cerr << "连接失败" << endl;
        exit(CONNECT_ERR);
    }

    char buffer[1024];
    while (true)
    {
        std::string line;
        cout << "please Enter# ";
        getline(cin, line);

        write(sock, line.c_str(), line.size());

        ssize_t s = read(sock, buffer, sizeof(buffer) - 1);
        if (s > 0)
        {
            buffer[s] = '\0';
            cout << "server echo# " << buffer << endl;
        }
        else if (s == 0)
        {
            cerr << "服务器崩溃" << endl;
            break;
        }
        else
        {
            cerr << "read error:" << strerror(errno) << endl;
            break;
        }
    }

    return 0;
}